#include "appinit.h"
#include <QMouseEvent>
#include <QWidget>

AppInit * AppInit::instance = nullptr;

AppInit *AppInit::getInstance()
{
    static QMutex mutex;
    if(!instance)
    {
        QMutexLocker locker(&mutex);
        if(!instance)
        {
            instance = new AppInit();
        }
    }
    return instance;
}

void AppInit::start()
{
    qApp->installEventFilter(this);

}

bool AppInit::eventFilter(QObject * obj, QEvent * evt)
{
    QWidget *w = (QWidget *)obj;

    //canMove == false
    if (!w->property("canMove").toBool()) {
        return QObject::eventFilter(obj, evt);
    }

    //canMove == true
    static QPoint mousePoint;
    static bool mousePressed = false;

    QMouseEvent *event = static_cast<QMouseEvent *>(evt);
    if (event->type() == QEvent::MouseButtonPress) {
        if (event->button() == Qt::LeftButton) {
            mousePressed = true;
            mousePoint = event->globalPos() - w->pos();
            return true;
        }
    } else if (event->type() == QEvent::MouseButtonRelease) {
        mousePressed = false;
        return true;
    } else if (event->type() == QEvent::MouseMove) {
        if (mousePressed && (event->buttons() && Qt::LeftButton)) {
            w->move(event->globalPos() - mousePoint);
            return true;
        }
    }

    return QObject::eventFilter(obj, evt);
}

AppInit::AppInit(QObject *parent) : QObject(parent)
{

}
